<template>
  <div class="visitor-register">
    <el-container class="layout-container">
      <!-- 头部 -->
      <el-header class="app-header">
        <div class="header-content">
          <h1 class="header-title">来访登记</h1>
        </div>
      </el-header>
      <CodeType v-if="isShow && !isEmpty" :form-data="detailData" @get-detail="getDetail" @reset="reset" />
      <!-- 主体内容 -->
      <el-main v-if="!isShow || isEmpty" class="app-main">
        <!-- 微信授权组件 -->
        <div class="main-container">
          <WechatAuth 
            v-if="!isWechatAuthorized"
            @auth-success="handleWechatAuthSuccess"
            @auth-error="handleWechatAuthError"
          />
        </div>
        <div class="main-container" v-if="isWechatAuthorized">
          <el-card class="form-card" shadow="hover">
            <el-form ref="formRef" :model="formData" :rules="formRules" label-width="120px" label-position="top"
              class="visitor-form">

              <el-row :gutter="20">
                <el-col :xs="24" :sm="12">
                  <el-form-item label="来访人员类别" prop="visitorType">
                    <el-select v-model="formData.visitorType" placeholder="请选择人员类别" style="width: 100%"
                      @change="handleVisitorTypeChange">
                      <el-option label="其他人员" value="other" />
                      <el-option label="施工人员" value="construction" />
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :xs="24" :sm="12">
                  <el-form-item label="企业联系人" prop="enterpriseContact">
                    <el-input v-model="formData.enterpriseContact" placeholder="请输入企业联系人" clearable />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="20">
                <el-col :xs="24" :sm="12">
                  <el-form-item label="公司名称" prop="LFRGSMC">
                    <el-input v-model="formData.LFRGSMC" placeholder="请输入公司名称" clearable />
                  </el-form-item>
                </el-col>
                <el-col :xs="24" :sm="12">
                  <el-form-item label="来访人员姓名" prop="visitorName">
                    <el-input v-model="formData.visitorName" placeholder="请输入姓名" clearable />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="20">
                <el-col :xs="24" :sm="12">
                  <el-form-item label="联系电话" prop="phone">
                    <el-input v-model="formData.phone" placeholder="请输入手机号码" clearable />
                  </el-form-item>
                </el-col>
                <el-col :xs="24" :sm="12">
                  <el-form-item label="来访人数" prop="visitorCount">
                    <el-input-number v-model="formData.visitorCount" :min="1" :max="100" placeholder="请输入来访人数"
                      style="width: 100%" />
                  </el-form-item>
                </el-col>
              </el-row>
<!-- 施工人员专属字段 -->
<div v-if="formData.visitorType === 'construction'" class="construction-section">
                <el-divider content-position="left">
                  <el-icon>
                    <Tools />
                  </el-icon>
                  施工信息
                </el-divider>

                <el-row :gutter="20">
                  <el-col :xs="24" :sm="12">
                    <el-form-item label="预计施工开始时间" prop="startDate">
                      <el-date-picker v-model="formData.startDate" type="date" placeholder="选择开始日期" style="width: 100%"
                        :disabled-date="disabledStartDate" />
                    </el-form-item>
                  </el-col>
                </el-row>

                <el-row :gutter="20">
                  <el-col :xs="24" :sm="12">
                    <el-form-item label="预计施工结束时间" prop="endDate">
                      <el-date-picker v-model="formData.endDate" type="date" placeholder="选择结束日期" style="width: 100%"
                        :disabled-date="disabledEndDate" />
                    </el-form-item>
                  </el-col>
                </el-row>

                <el-alert title="施工时间周期单次填写不允许超过10天" type="info" :closable="false" show-icon />
              </div>
              <el-row :gutter="20">
                <el-col :xs="24" :sm="12">
                  <el-form-item label="进场事由" prop="purpose">
                    <el-input 
                      v-model="formData.purpose" 
                      placeholder="请填写进场事由" 
                      clearable 
                      type="textarea"
                      :rows="3"
                    />
                    <div class="voice-input-section">
                      <VoiceTranscriber 
                        @transcription-update="handleTranscriptionUpdate"
                        :websocket-url="'wss://keda119.kedacom.com/ws/v1'"
                        :max-duration="120"
                      />
                    </div>
                  </el-form-item>
                </el-col>
                <el-col :xs="24" :sm="12">
                  <el-form-item label="访问公司名称" prop="QYMC">
                    <el-input v-model="formData.QYMC" placeholder="请输入访问公司名称" disabled />
                  </el-form-item>
                </el-col>
              </el-row>
              

              <el-form-item class="form-actions">
                <el-button type="primary" @click="submitForm" :loading="loading" size="large">
                  {{ loading ? "提交中..." : "保存" }}
                </el-button>
              </el-form-item>
            </el-form>
          </el-card>
        </div>
      </el-main>
    </el-container>
  </div>
</template>

<script setup lang="ts">
import CodeType from "~/components/outsource-operation/CodeType.vue";
import WechatAuth from "~/components/WechatAuth.vue";
import VoiceTranscriber from "~/components/VoiceTranscriber.vue";
import moment from 'moment'
import { onMounted, computed, reactive, ref } from "vue";
import { ElMessage, type FormInstance, type FormRules } from "element-plus";
import { Tools } from "@element-plus/icons-vue";
import { saveApi, getInfoByCodeApi, getTokenApi } from "~/composables/useOutsourceOperation";
import type { VisitorInfo } from "~/types/api";
import { useAppStore } from "~/stores/app";

const router = useRouter();
const route = useRoute();
const formRef = ref<FormInstance>();
const loading = ref(false);
const isShow = ref(false);
const isEmpty = ref(true);
const detailData = ref<Partial<VisitorInfo>>({});
const isWechatAuthorized = ref(false);
const wechatUserInfo = ref<any>({});
const config = useRuntimeConfig()
const appid = config.public.wechatAppId
const appkey=ref(appid)
// 统一错误提示
const showError = (msg: string) => ElMessage.error(msg || "请求失败，请重试");
const today = computed(() => {
  return new Date().toISOString().split("T")[0];
});

// 微信授权成功处理
const handleWechatAuthSuccess = (data: any) => {
  console.log('微信授权成功:', data);
  isWechatAuthorized.value = true;
  wechatUserInfo.value = data;
  ElMessage.success('微信授权成功！');
};

// 微信授权失败处理
const handleWechatAuthError = (error: string) => {
  console.error('微信授权失败:', error);
  ElMessage.error(`微信授权失败: ${error}`);
};

// 语音转写文本更新处理
const handleTranscriptionUpdate = (text: string) => {
  formData.purpose = text;
  ElMessage.success('语音转写完成，已自动填入进场事由');
};

// 组件挂载
onMounted(async () => {
  // 检查是否已经有微信授权信息
  const urlParams = new URLSearchParams(process.client ? window.location.search : '');
  const code = urlParams.get('code');
  const fromWechat = urlParams.get('fromWechat');
  
  // 检查sessionStorage中是否有微信用户信息
  if (process.client) {
    const storedWechatInfo = sessionStorage.getItem('wechatUserInfo');
    
    if (fromWechat === 'true' && storedWechatInfo) {
      // 从微信授权回调回来，且有存储的用户信息
      isWechatAuthorized.value = true;
      wechatUserInfo.value = JSON.parse(storedWechatInfo);
      console.log('从sessionStorage获取微信用户信息:', wechatUserInfo.value);
    } else if (code) {
      // 如果有code参数，说明是从微信授权回调回来的，直接显示表单
      isWechatAuthorized.value = true;
    }
  }
  
  await getToken();
  await leasedMgntLogin();
});

// 重新填写
const reset = () => {
  getDetail(true);
};

// 获取token
const getToken = async () => {
  try {
    const response = await getTokenApi();

    if (response.code === "-1") {
      showError(response.message || "获取token失败");
      return;
    }
    if (response.result) {
      // 这里应该设置到store中，但需要先配置store
      console.log("Token获取成功:", response.result.AJDLXX);
      const appStore = useAppStore();
      appStore.setUserToken(response.result.AJDLXX);
    }
  } catch (error) {
    console.error("获取token失败:", error);
    showError("获取token失败，请重试");
  }
};

// 租赁管理登录
const leasedMgntLogin = async () => {
  try {
    await getDetail();
  } catch (error) {
    console.error("登录失败:", error);
    showError("登录失败，请重试");
  }
};

// 获取访客详情
const getDetail = async (reset = false): Promise<void> => {
  try {
    // 从路由参数中获取WXID和QYBH
    const params = route.query;
    const api = getInfoByCodeApi;
    const response = await api(params);
    if (response.code === "-1") {
      showError(response.message || "获取详情失败");
      return;
    }
    isShow.value = true;
    if (!reset && response.result) {
      detailData.value = response.result;
      // 检查通行证是否过期
      if (
        detailData.value.YXQJSSJ &&
        new Date(String(detailData.value.YXQJSSJ) + " 23:59:59") < new Date()
      ) {
        isEmpty.value = true;
        detailData.value = {};
      } else {
        isEmpty.value = false;
      }
    } else {
      isEmpty.value = true;
    }
  } catch (error) {
    console.error("获取详情失败:", error);
    showError("获取详情失败，请重试");
  }
};

const formData = reactive({
  visitorType: "",
  enterpriseContact: "",
  LFRGSMC: "", // 公司名称（来访人公司）
  QYMC: route.query.QYMC as string, // 访问公司名称
  visitorName: "",
  phone: "",
  visitorCount: 1,
  purpose: "",
  startDate: today,
  endDate: "",
});

const formRules: FormRules = {
  visitorType: [
    { required: true, message: "请选择来访人员类别", trigger: "change" },
  ],
  LFRGSMC: [{ required: true, message: "请输入公司名称", trigger: "blur" }],
  QYMC: [{ required: true, message: "请选择访问公司", trigger: "change" }],
  visitorName: [
    { required: true, message: "请输入来访人员姓名", trigger: "blur" },
  ],
  phone: [
    { required: true, message: "请输入联系电话", trigger: "blur" },
    {
      pattern: /^1[3-9]\d{9}$/,
      message: "请输入正确的手机号码",
      trigger: "blur",
    },
  ],
  visitorCount: [
    { required: true, message: "请输入来访人数", trigger: "blur" },
    { type: "number", min: 1, message: "人数必须大于0", trigger: "blur" },
  ],
  purpose: [{ required: true, message: "请输入进场事由", trigger: "blur" }],
   
  startDate: [
    { required: true, message: "请选择施工开始时间", trigger: "change" },
  ],
  endDate: [
    { required: true, message: "请选择施工结束时间", trigger: "change" },
  ],
};

const handleVisitorTypeChange = (value: string) => {
  if (value !== "construction") {
    formData.startDate = "";
    formData.endDate = "";
  }
};

const disabledStartDate = (time: Date) => {
  return time.getTime() < Date.now() - 8.64e7; // 不能选择今天之前的日期
};

const disabledEndDate = (time: Date) => {
  if (!formData.startDate) return time.getTime() < Date.now() - 8.64e7;
  const startDate = new Date(formData.startDate);
  const maxDate = new Date(startDate);
  maxDate.setDate(startDate.getDate() + 10);
  return (
    time.getTime() < startDate.getTime() || time.getTime() > maxDate.getTime()
  );
};

const validateForm = async (): Promise<boolean> => {
  if (!formRef.value) return false;

  try {
    await formRef.value.validate();

    // 额外的施工人员验证
    if (formData.visitorType === "construction") {
      const start = new Date(formData.startDate as string);
      const end = new Date(formData.endDate as string);
      const diffDays = Math.ceil(
        (end.getTime() - start.getTime()) / (1000 * 60 * 60 * 24)
      );

      if (diffDays > 10) {
        ElMessage.error("施工时间周期单次填写不允许超过10天");
        return false;
      }
    }

    return true;
  } catch {
    return false;
  }
};

const submitForm = async () => {
  if (!(await validateForm())) {
    return;
  }

  loading.value = true;

  try {
    const params = {
      WXID: wechatUserInfo.value.openid || route.query.CODE as string, // 微信ID，优先使用微信授权的openid
      RYLX:{
       ID: formData.visitorType === "construction" ? "1" : "99",
       VALUE: formData.visitorType === "construction" ? "施工人员" : "其他人员",
      },
      LFRGSMC: formData.LFRGSMC,
      XM: formData.visitorName,
      LXDH: formData.phone,
      RS: formData.visitorCount.toString(),
      JCSY: formData.purpose,
      QYBH: route.query.QYBH as string, // 企业编号
      QYMC: formData.QYMC, // 访问公司名称
      ...(formData.visitorType === "construction" && {
        YJSGKSSJ: formData.startDate,
        YJSGJSSJ: moment(formData.endDate).format("YYYY-MM-DD"),
      }),
    };

    const response = await saveApi(params);

    if (response.code === "-1") {
      ElMessage.error(response.message || "提交失败");
      return;
    }
    ElMessage.success("登记成功！");
    await getDetail()
    
  } catch (error) {
    console.error("提交失败:", error);
    ElMessage.error("提交失败，请稍后重试");
  } finally {
    loading.value = false;
  }
};

const goBack = () => {
  router.back();
};
</script>

<style scoped>
.visitor-register {
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.layout-container {
  min-height: 100vh;
}

.app-header {
  background: transparent;
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  /* padding: 2rem 0; */
}

.header-content {
  text-align: center;
}

.header-title {
  font-size: 2.5rem;
  margin-bottom: 0.5rem;
  font-weight: 300;
  text-shadow: 0 2px 4px rgba(0, 0, 0, 0.3);
}

.header-subtitle {
  font-size: 1.1rem;
  opacity: 0.9;
  margin: 10;
}

.app-main {
  padding: 2rem 0;
  background: #f5f7fa;
}

.main-container {
  max-width: 880px;
  margin: 0 auto;
  padding: 0 20px;
}

.form-card {
  margin-bottom: 2rem;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-title {
  font-size: 1.25rem;
  font-weight: 600;
  color: #303133;
}

.visitor-form {
  padding: 1rem 0;
}

.construction-section {
  margin-top: 2rem;
  padding: 1.5rem;
  background: #f8f9fa;
  border-radius: 8px;
  border-left: 4px solid #409eff;
}

.voice-input-section {
  margin-top: 1rem;
  padding: 1rem;
  background: #f8f9fa;
  border-radius: 8px;
  border: 1px solid #e0e0e0;
}

.form-actions {
  margin-top: 2rem;
  text-align: center;
}

.form-actions .el-button {
  min-width: 120px;
  margin: 0 10px;
}

.app-footer {
  background: #303133;
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 1rem 0;
}

.footer-content {
  text-align: center;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .main-container {
    padding: 0 12px;
  }

  .header-title {
    font-size: 2rem;
  }

  .header-subtitle {
    font-size: 1rem;
  }

  .card-header {
    flex-direction: column;
    gap: 1rem;
    align-items: flex-start;
  }

  .construction-section {
    padding: 1rem;
  }

  .form-actions .el-button {
    width: 100%;
    margin: 8px 0;
  }
}
</style>
